<template>
  <div>
    <VxeTableVue
      ref="tableEl"
      module-name="代理"
      :queryFormData="state.formData"
      :column-config="columnConfig"
      data-list-api="/agent/version/page"
      delete-api="/agent/version"
      update-or-add-api="/agent/version"
      del-permi="admin-agent-del"
      add-permi="admin-agent-add"
      update-permi="admin-agent-update"
      :show-action-column="hasPermi(['admin-agent-update', 'admin-agent-del', 'admin-agent-publish-recorde', 'admin-agent-publish'])"
      :add-data="state.addItemData"
      :dialog-form-rules="rules"
      :dialog-width="600"
      :action-column-width="240"
      @refactor-dialog-params="onBeforeSubmit"
      @before-open-dialog="onBeforeOpenDialog"
    >
      <!------------------------------------------ 查询 ------------------------------------------------------->

      <template #queryItem>
        <el-form-item label="代理版本" prop="agentVersion" class="mgr30">
          <el-input v-model="state.formData.agentVersion" placeholder="代理版本" clearable />
        </el-form-item>
      </template>

      <!------------------------------------------ 列表 ------------------------------------------------------->
      <template #agentStatus="{ row }: SlotRow">
        <el-tag :type="row.publishRecord?.length ? 'success' : 'warning'">{{ row.publishRecord?.length ? '已发布' : '未发布' }}</el-tag>
      </template>

      <!-- <template #publishRecord="{ row }: SlotRow">
        <el-link type="primary">{{ mapRecord(row).join(',') }}</el-link>
      </template> -->

      <template #extraBtn2="{ row }: SlotRow">
        <el-button v-has-permi="['admin-agent-publish']" type="primary" link @click="handlePublish(row)">发布</el-button>
        <el-button v-has-permi="['admin-agent-publish-record']" v-show="row.publishRecord?.length" type="primary" link @click="checkRecord(row)">发布记录</el-button>
      </template>

      <!------------------------------------------ 新增修改 ------------------------------------------------------->

      <template #dialogUpdateOrAdd="{ row }: SlotRow">
        <div class="flex" style="width: 80%">
          <div class="flex mgl30 mgb20">
            <span style="color: red">*</span>
            <span class="mgl5">代理文件：</span>
          </div>
          <UploadButton
            ref="uploadEl"
            class="flex1"
            v-model="state.fileList"
            accept=".zip"
            :limit="1"
            :on-exceed="handleExceed"
            :auto-upload="false"
            action="/sys-file/upload"
            :on-success="onUploadSuccess"
            :before-remove="onRemoveFile"
            :on-error="onUploadErroe"
          >
            <template #trigger>
              <SvgIcon color="#3E72EB" name="upload" :width="17" :height="17" />
            </template>
          </UploadButton>
        </div>
        <el-row class="flex mgt20">
          <el-form-item label="代理版本" prop="agentVersion" class="mgr30 flex1" label-width="100">
            <el-input v-model="row.agentVersion" placeholder="代理版本" clearable />
          </el-form-item>
        </el-row>
        <el-row class="flex mgt20">
          <el-form-item label="可升级版本" prop="allowedVersion" class="mgr30 flex1" label-width="100">
            <el-input v-model="row.allowedVersion" placeholder="可升级版本" clearable />
          </el-form-item>
        </el-row>
        <el-row class="flex mgt20">
          <el-form-item label="代理描述" prop="description" class="mgr30 flex1" label-width="100">
            <el-input v-model="row.description" type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" placeholder="代理描述" clearable />
          </el-form-item>
        </el-row>
      </template>
    </VxeTableVue>

    <!------------------------------------------ 弹窗 ------------------------------------------------------->

    <DialogVue ref="publishEl" title="发布" @before-submit="handleSave">
      <Publish ref="publishInfoEl" :data="state.currentPublishData" @publish-success="onPublishSuccess" @loading-change="publishEl?.setLoading($event)" />
    </DialogVue>

    <DialogVue ref="recordTableEl" title="发布记录" :width="1000" :showConfirmBtn="false">
      <div class="width-all mgb30" v-for="(item, index) in state.currentRow.publishRecord" :key="index">
        <el-descriptions class="margin-top" :column="3" border>
          <template #title>
            <div class="flex-row-center-left gap30">
              <span>版本：{{ state.currentRow.agentVersion }}</span>
              <span>发布人：{{ item.createBy }}</span>
              <span>发布日期：{{ item.createTime }}</span>
            </div>
          </template>
          <template v-for="data in item.agentJson" :key="data">
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">客户</div>
              </template>
              {{ data.customerName }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">产线号</div>
              </template>
              {{ data.productionLineId }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">客户机号</div>
              </template>
              {{ data.customerClientId }}
            </el-descriptions-item>
          </template>
        </el-descriptions>
      </div>
    </DialogVue>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue'
  import { VxeTableVue, type VxeTableViewInstance } from '@/components/table'
  import DialogVue, { type DialogVueInstance } from '@/components/dialog'
  import Publish from './cpns/publish.vue'
  import { UploadButton, type UploadButtonInstance } from '@/components/upload'
  import { columnConfig, type SlotRow, type AgentVersion } from './config'
  import { Ui, hasPermi } from '@/utils'
  import request, { type IApiData } from '@/service'

  const tableEl = ref<VxeTableViewInstance>()
  const uploadEl = ref<UploadButtonInstance>()
  const publishEl = ref<DialogVueInstance>()
  const recordTableEl = ref<DialogVueInstance>()
  const publishInfoEl = ref<InstanceType<typeof Publish>>()

  const initAddData = (): Partial<AgentVersion> => {
    return {
      id: '',
      agentVersion: '',
      description: '',
      allowedVersion: '',
      sysFileId: '',
      fileUrl: ''
    }
  }

  const state = reactive({
    dialogType: '',
    fileList: [] as any[],
    formData: {
      agentVersion: ''
    },
    addItemData: initAddData(),
    updateData: {} as AgentVersion,
    currentPublishData: {} as AgentVersion,
    currentRow: {
      publishRecord: []
    } as Partial<AgentVersion>
  })

  const rules = {
    agentVersion: [{ required: true, message: '请输入代理版本', trigger: 'blur' }]
  }

  /**----------------------------methods----------------------------------------------------------------------- */

  const checkRecord = (row: AgentVersion) => {
    state.currentRow = row
    recordTableEl.value?.handleOpen()
  }

  const handlePublish = (row: AgentVersion) => {
    state.currentPublishData = row
    publishEl.value?.handleOpen()
  }

  const onPublishSuccess = () => {
    publishEl.value?.handleClose()
    reflesh()
  }

  const handleSave = (_: any, fn: any) => {
    fn(false)
    publishInfoEl.value?.handlePublish()
  }

  // const mapRecord = (data: AgentVersion) => {
  //   if (!data.publishRecord?.length) return []
  //   return data.publishRecord?.reduce((pre, cur) => {
  //     const customerNames = cur.agentJson.map(item => item.customerName)
  //     pre = pre.concat(customerNames)
  //     return pre
  //   }, [] as string[])
  // }

  /**
   *  打开新增修改弹窗
   * @param type
   * @param data
   */
  const onBeforeOpenDialog = (type: 'update' | 'add', data: AgentVersion) => {
    state.dialogType = type
    if (type === 'update') {
      state.updateData = data
      state.fileList = [{ name: data.sysFileOriginal, url: data.fileUrl }]
    } else {
      for (const k in data) {
        //@ts-ignore
        data[k] = ''
      }
      state.fileList = []
    }
  }

  const onBeforeSubmit = (type: 'update' | 'add', data: any, fn: any) => {
    fn(false)

    if (!state.fileList.length) return Ui.useMessage('warning', '请先选择代理文件')

    if (state.dialogType === 'update' && !state.fileList[0].raw) return saveAgent()

    tableEl.value?.setDialogLoading(true)
    uploadEl.value?.handleSubmit()
  }

  interface ResData {
    bucketName: string
    fileName: string
    originalFileName: string
    id: string
    url: string
  }
  const onUploadSuccess = (res: IApiData<ResData>) => {
    if (res.code !== 0) return Ui.useMessage('warning', res.msg)
    const key = state.dialogType === 'add' ? 'addItemData' : 'updateData'
    state[key].fileUrl = res.data.url
    state[key].sysFileId = res.data.id
    state[key].sysFileOriginal = res.data.originalFileName

    saveAgent()
  }

  const onUploadErroe = () => {
    Ui.useMessage('error', '上传失败，请重新选择文件上传')
    tableEl.value?.setDialogLoading(false)
  }

  const onRemoveFile = () => {
    tableEl.value?.setDialogLoading(false)
  }

  const handleExceed = (file: any[]) => {
    uploadEl.value?.clearFiles()
    uploadEl.value?.setFiles(file[0])
  }

  /**
   * 保存代理
   */
  const saveAgent = () => {
    tableEl.value?.setDialogLoading(true)
    const method = state.dialogType === 'add' ? 'post' : 'put'
    const params = state.dialogType === 'add' ? state.addItemData : state.updateData

    request[method]('/agent/version', params)
      .then(res => {
        if (res.code !== 0) return Ui.useMessage('error', res.msg)

        state.addItemData = initAddData()
        state.fileList = []

        tableEl.value?.handleCloseDialog()

        reflesh()
      })
      .finally(() => tableEl.value?.setDialogLoading(false))
  }

  const reflesh = () => tableEl.value?.query()

  /**----------------------------lifecycle----------------------------------------------------------------------- */
</script>

<style scoped lang="less">
  ::deep(.el-descriptions__label) {
    width: 80px !important;
  }
</style>
